package com.pactera.madp.cp.service.impl;

import com.pactera.madp.common.core.exception.CheckedException;
import com.pactera.madp.common.data.tenant.TenantContextHolder;
import com.pactera.madp.common.security.util.SecurityUtils;
import com.pactera.madp.cp.api.entity.WorkEmployeeEntity;
import com.pactera.madp.cp.common.util.RedisUtil;
import com.pactera.madp.cp.handler.CorpContextHolder;
import com.pactera.madp.cp.service.IWorkEmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class AccountService {

    private static final String TYPE_CORP_ID = "corpId";
    private static final String TYPE_EMPLOYEE_ID = "employeeId";
    private static final String REDIS_PREFIX_CORP = "cp:user.corp.%d.%d";
    private static final String REDIS_PREFIX_EMP = "cp:user.emp.%d.%d";
    //cp:user.corp
    private static final String REDIS_CORP_ACCESS_TOKEN = "cp:corp_token:%d.%d";

    private static IWorkEmployeeService employeeService;

    @Autowired
    public void setEmployeeService(IWorkEmployeeService employeeService) {
        AccountService.employeeService = employeeService;
    }

    /**
     * 获取当前企业的id
     * @return
     */
    public static Integer getCorpId() {
        int userId = getUserId();
        Integer corpId = (Integer) RedisUtil.get(String.format(REDIS_PREFIX_CORP, userId, CorpContextHolder.getCorpId()));
        if(corpId == null || corpId < 1) {
            getNewId(userId, TYPE_CORP_ID);
        }
        return corpId;
    }

    /**
     * 获取当前企业成员的id
     * @return
     */
    public static Integer getEmpId() {
        int userId = getUserId();
        Integer empId = (Integer) RedisUtil.get(String.format(REDIS_PREFIX_EMP, userId, CorpContextHolder.getCorpId()));
        if (empId == null || empId < 1) {
            empId = getNewId(userId, TYPE_EMPLOYEE_ID);
        }
        return empId;
    }

    /**
     * 获取当前子账户Id
     * @return
     */
    public static Integer getUserId() {
        //Integer userId = (Integer) JwtUtil.parseJWT(getToken()).get("userId");
        Integer userId = SecurityUtils.getUser().getId();
        if (userId == null || userId < 1) {
            throw new CheckedException("非法token");
        }
        return userId;
    }


    private static Integer getNewId(int userId, String type) {
        List<WorkEmployeeEntity> employeeList = employeeService.getWorkEmployeeByLogUserId(userId);
        if (employeeList == null || employeeList.isEmpty()) {
            throw new CheckedException("未找到所属企业信息");
        }

        Integer corpId = CorpContextHolder.getCorpId();
        for(WorkEmployeeEntity employee : employeeList) {
            if(employee.getCorpId() == corpId) {
                updateCorpIdAndEmployeeId(userId, corpId, employee.getId());
            }
        }

        String key = "";
        switch (type) {
            case TYPE_CORP_ID:
                key = String.format(REDIS_PREFIX_CORP, userId, corpId);
                return (Integer) RedisUtil.get(key);
            case TYPE_EMPLOYEE_ID:
                key = String.format(REDIS_PREFIX_EMP, userId, corpId);
                return (Integer) RedisUtil.get(key);
            default:
                return 0;
        }
    }

    public static void updateCorpIdAndEmployeeId(int userId, int corpId, int employeeId) {
        RedisUtil.set(String.format(REDIS_PREFIX_CORP, userId,corpId), corpId, 1800);
        RedisUtil.set(String.format(REDIS_PREFIX_EMP, userId, corpId), employeeId, 1800);
    }


    /**
     * @author: yangpengwei
     * @time: 2021/3/12 2:52 下午
     * @description 获取用户的租户 id
     */
    public static int getTenantId() {
        return TenantContextHolder.getTenantId();
    }

    /**
     * 检验访问权限
     * @return
     */
    public static Boolean isAuthority() {
        String username = SecurityUtils.getUser().getUsername();
        if ("admin".equals(username))
            return true;
        Integer userId = SecurityUtils.getUser().getId();
        Integer corpId = CorpContextHolder.getCorpId();
        String accessTokenKey = String.format(REDIS_CORP_ACCESS_TOKEN,userId,corpId);
        Long expire = RedisUtil.getExpire(accessTokenKey);

        if(expire > 0) {
            return true;
        }
        else if(expire == null || expire <= 0) {
            //刷新token
            List<WorkEmployeeEntity> employeeList = employeeService.getWorkEmployeeByLogUserId(userId);
            if (employeeList == null || employeeList.isEmpty()) {
                //throw new CheckedException("未找到所属企业信息");
                log.error("认证未通过：未找到所属企业信息");
                return false;
            }
            for(WorkEmployeeEntity employee : employeeList) {
                if(employee.getCorpId() == corpId) {
                    setCorpAccessToken(userId, corpId, employee.getId());
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 为企业成员管理员设置accessToken
     * @param userId
     * @param corpId
     * @param employeeId
     */
    public static void setCorpAccessToken(int userId, int corpId, int employeeId) {
        RedisUtil.set(String.format(REDIS_CORP_ACCESS_TOKEN, userId, corpId), employeeId, 1800);
    }



}
